package com.yunda.util;

import android.util.Log;

import com.alibaba.fastjson.util.IOUtils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Collections;
import java.util.List;

/**
 * copyright (C), 2022, 运达科技有限公司
 * fileName CopyUtil
 *
 * @author 王玺权
 * date 2022-05-16 1:52
 * description
 * history
 */
public class CopyUtil {
    public static  <T> List<T> deepCopy(List<T> src) {
        ByteArrayOutputStream byteOut = null;
        ObjectOutputStream out = null;
        ByteArrayInputStream byteIn = null;
        ObjectInputStream in = null;
        try {
            byteOut = new ByteArrayOutputStream();
            out = new ObjectOutputStream(byteOut);
            out.writeObject(src);
            byteIn = new ByteArrayInputStream(byteOut.toByteArray());
            in = new ObjectInputStream(byteIn);
            return (List<T>) in.readObject();
        } catch (Exception ex) {
            ex.printStackTrace();
            Log.e("深拷贝异常", ex.getMessage());
        } finally {
            IOUtils.close(in);
            IOUtils.close(byteIn);
            IOUtils.close(out);
            IOUtils.close(byteOut);
        }
        return Collections.emptyList();
    }

    public static <T>T deepCopyObj(T src) {
        ByteArrayOutputStream byteOut = null;
        ObjectOutputStream out = null;
        ByteArrayInputStream byteIn = null;
        ObjectInputStream in = null;
        try {
            byteOut = new ByteArrayOutputStream();
            out = new ObjectOutputStream(byteOut);
            out.writeObject(src);
            byteIn = new ByteArrayInputStream(byteOut.toByteArray());
            in = new ObjectInputStream(byteIn);
            return (T) in.readObject();
        } catch (Exception ex) {
            ex.printStackTrace();
            Log.e("深拷贝异常", ex.getMessage());
        } finally {
            IOUtils.close(in);
            IOUtils.close(byteIn);
            IOUtils.close(out);
            IOUtils.close(byteOut);
        }
        return null;
    }
}
